/* 
 * File:   main.c
 * Author: kovacshuni
 *
 * Created on March 18, 2011, 12:27 AM
 */

#include <stdio.h>
#include <stdlib.h>

char* INPUT_FILE = "Sorting.in";
char* OUTPUT_FILE = "Sorting.out";
int MAX_REC_LEN = 1024;

void merge(int* list_left, int* list_right, int length_left, int length_right, int** result) {

    int i_left = 0, i_right = 0;

    while ((i_left < length_left) || (i_right < length_right)) {
        if ((i_left < length_left) && (i_right < length_right)) {
            if (list_left[i_left] < list_right[i_right]) {
                *(*result + i_left + i_right) = list_left[i_left++];
            } else {
                *(*result + i_left + i_right) = list_right[i_right++];
            }
        } else if (i_left < length_left) {
            *(*result + i_left + i_right) = list_left[i_left++];
        } else if (i_right < length_right) {
            *(*result + i_left + i_right) = list_right[i_right++];
        }
    }
}


void merge_sort(int** list, int length_list) {
    if (length_list <= 1) {
        return;
    }

    int length_left, length_right;

    length_left = length_list / 2;
    if (length_list % 2 == 0) {
        length_right = length_left;
    } else {
        length_right = length_left + 1;
    }

    int** list_left;
    int** list_right;

    list_left = (int**) malloc(1 * sizeof(int*));
    *list_left = (int*) malloc(length_left * sizeof(int));
    list_right = (int**) malloc(1 * sizeof(int*));
    *list_right = (int*) malloc(length_right * sizeof(int));

    int i;
    for (i = 0; i < length_left; i++) {
        (*list_left)[i] = (*list)[i];
    }
    for (i = length_left; i < length_list; i++) {
        (*list_right)[i - length_left] = (*list)[i];
    }

    merge_sort(list_left, length_left);
    merge_sort(list_right, length_right);
    merge(*list_left, *list_right, length_left, length_right, list);
}

void read(int*** list) {
    FILE* in_file = fopen(INPUT_FILE, "r");
    char* line = (char*) malloc(MAX_REC_LEN);
    int i = 0;
    while (fgets(line, MAX_REC_LEN, in_file)) {
        (*list)[i] = (int*) malloc(MAX_REC_LEN * sizeof(int));
        //while ()
        sscanf(line, "%d", ((*list)[i]) + j);
        i++;
    }

    fclose(in_file);
}

/*
 * 
 */
int main(int argc, char** argv) {

    return (EXIT_SUCCESS);
}

